<html>
<body>
<input  id="input"/>
<button id="click">点击</button>
<script>
    /*
     复杂json转为FormData
     parent:key值，data:数据值，form:FormData实例
     使用：JsonToFormData("", a, null);
     */
    function JsonToFormData(parent, data, form) {
        form = form || new FormData();
        //循环传入的值转换formData
        let index = 0;
        Object.keys(data).forEach((key) => {
            let val = data[key];
            // console.log(key, typeof val, val.length);
            if (val == null) {
                let pk = parent ? parent[key] : key;
                form.append(pk, val);
            }
            else if (typeof val === "object") {
                if (val.length == 0) { }
                else if (val.length >= 1) {
                    //数组
                    let pk = parent ? parent[index][key] : key;
                    JsonToFormData(pk, val, form);
                } else {
                    //纯对象
                    let pk = parent ? parent[key] : key;
                    JsonToFormData(pk, val, form);
                }
            } else {
                let pk = parent ? parent[key] : key;
                form.append(pk, val);
            }
            index++;
        });
        if (parent == "") return form;
    }
    document.getElementById("click").onclick = function () {
        let params1 = document.getElementById("input").value;
        console.log(params1);
        let params = JSON.parse(params1);
        let a = JsonToFormData("", params, null);
        console.log(a);
        for (let [key, value] of a) {
            console.log(key+":"+value);
        }
    }
</script>
<!--<script>-->
<!--    document.getElementById("click").onclick = function () {-->
<!--        let params1 = document.getElementById("input").value;-->
<!--        console.log(params1);-->
<!--        let params = JSON.parse(params1);-->
<!--        console.log(params);-->
<!--        const formData = new FormData();-->
<!--        Object.keys(params).forEach((key) => {-->
<!--            if (typeof params[key] == 'string') {-->
<!--                formData.append(key, params[key])-->
<!--                console.log(formData);-->
<!--            } else {-->
<!--                formData.append(key, JSON.stringify(params[key]))-->
<!--            }-->
<!--            // console.log(key);-->
<!--        })-->
<!--        console.log(formData);-->
<!--    }-->
<!--</script>-->
</body>
</html>

